package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.basic.web.repository.UserGroupRepository;
import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.UserGroupParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.UserGroupPO;
import com.tarena.lbs.pojo.basic.query.UserGroupQuery;
import com.tarena.lbs.pojo.basic.vo.UserGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserGroupService {
    @Autowired
    private UserGroupRepository userGroupRepository;
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) throws BusinessException {
        //1.获取用户认证对象 用户认证解析失败
        Integer adminId=getUserId();
        //2.查询adminPO 获取businessId 没有商家
        Integer businessId = checkAndGetBusinessId(adminId);
        //3.获取当前商家的用户人群列表
        List<UserGroupPO> pos=getUserGroupsByBizId(businessId);
        //4.封装分页返回
        PageResult<UserGroupVO> voPage=assemblePage(pos);
        log.info("用户人群 分页查询结果:{}",voPage);
        return voPage;
    }

    private PageResult<UserGroupVO> assemblePage(List<UserGroupPO> pos) {
        PageResult<UserGroupVO> voPage=new PageResult<>(10,1);
        voPage.setTotal(100l);
        if (pos!=null&&pos.size()>0){
            log.info("命中的用户人群不为空,值:{}",pos);
            voPage.setObjects(pos.stream().map(po->{
                UserGroupVO vo=new UserGroupVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList()));
        }
        return voPage;
    }

    private List<UserGroupPO> getUserGroupsByBizId(Integer businessId) {
        //select * from lbs_user_grou where business_id=?
        QueryWrapper<UserGroupPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("business_id",businessId);
        return userGroupRepository.list(queryWrapper);
    }

    @Autowired
    private AdminRepository adminRepository;
    private Integer checkAndGetBusinessId(Integer adminId) throws BusinessException {
        AdminPO adminPO = adminRepository.getById(adminId);
        Asserts.isTrue(adminPO==null,new BusinessException("-2","后台账号不存在"));
        return adminPO.getBusinessId();
    }

    private Integer getUserId() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","认证解析失败"));
        return userPrinciple.getId();
    }

    public void save(UserGroupParam param) throws BusinessException {
        Integer userId = getUserId();
        Integer businessId = checkAndGetBusinessId(userId);
        checkDuplicate(param.getGroupName(),businessId);
        UserGroupPO po=param2po(param,businessId);
        userGroupRepository.save(po);
    }

    private UserGroupPO param2po(UserGroupParam param, Integer businessId) {
        UserGroupPO po=new UserGroupPO();
        BeanUtils.copyProperties(param,po);
        //补充businessId
        po.setBusinessId(businessId);
        //补充createAt创建时间
        po.setCreateAt(new Date());
        return po;
    }

    public void checkDuplicate(String groupName,Integer businessId) throws BusinessException {
        //select count() from lbs_user_group
        //where group_name=? and business_id=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("group_name",groupName);
        queryWrapper.eq("business_id",businessId);
        long count = userGroupRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","用户人群名称重复"));
    }
}
